<template>
  <div class="account-table">
    <slot name="search"></slot>
    <div class="table-box">
      <vxe-table
        align="center"
        size="medium"
        highlight-hover-row
        resizable
        border
        stripe
        row-key
        :data="tableList"
        :header-cell-class-name="headerStyle"
        :row-class-name="rowClass"
        height="100%"
        class="table-con"
        ref="xTable">
        <vxe-column type="seq" title="序号" width="60" class-name="drag-btn" key="seq"></vxe-column>
        <vxe-column field="userName" title="用户名" min-width="120" class-name="drag-btn">
          <template #default="{ row }">
            <div class="triangle-tips top-left bg-red" v-if="row.isMainLead == '1'">
              <span>
                <em>负责人</em>
              </span>
            </div>
            {{ row.userName }}
          </template>
        </vxe-column>
        <vxe-column field="loginName" title="登录账号" min-width="120"></vxe-column>
        <vxe-column field="orgName" title="所属机构" min-width="160"></vxe-column>
        <vxe-column field="postName" title="担任职位" min-width="160"></vxe-column>
        <vxe-column field="telephone" title="手机号" min-width="140">
          <template #default="{ row }">
            {{ row.telephone }}
          </template>
        </vxe-column>
        <vxe-column field="createTime" title="创建时间" sortable width="160"></vxe-column>
        <vxe-column field="userStatusName" title="状态" width="120"></vxe-column>
        <vxe-column field="oper" fixed="right" title="操作" width="120" v-if="postCode === 'current'" key="oper">
          <template #default="{ row }">
            <div>
              <el-button type="text" style="color: #2b78f1" @click.stop="editAccount(row)">编辑</el-button>
              <el-button type="text" style="color: #2b78f1" @click="delAccount(row)">删除</el-button>
            </div>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <slot name="pagination"></slot>
  </div>
</template>
<script>
import { formatDate } from '@utility/utility.js'
import { USER_STATUS } from '@utility/dict.js'
import Sortable from 'sortablejs'
export default {
  name: 'AccountTable',
  emits: ['del-account', 'edit-account', 'drop-account', 'update-account'],
  props: {
    source: {
      type: Array,
      default: () => [],
    },
    postCode: {
      type: String,
      default: 'current',
    },
  },
  data() {
    return {
      statusTags: USER_STATUS._tag,
      sortable2: null,
      tableList: [],
    }
  },
  watch: {
    source: {
      handler(newVal) {
        if (newVal.length) {
          if (this.sortable2) {
            this.sortable2.destroy()
          }
          this.treeDrop()
          this.tableList = newVal
          // console.log('newVal :>> ', newVal)
        } else {
          this.tableList = []
        }
      },
      deep: true,
      immediate: true,
    },
  },
  filters: {
    filterDate(obj) {
      let expiredTime = ''
      if (localStorage.PSKH_USERINFO && JSON.parse(localStorage.PSKH_USERINFO)) {
        const userInfo = JSON.parse(localStorage.PSKH_USERINFO)
        expiredTime = userInfo.endTime || ''
        expiredTime = expiredTime ? formatDate(new Date(expiredTime), 'yyyy-MM-dd') : ''
      }
      if (expiredTime) {
        const times = expiredTime.split('-')
        return `${times[0]}年${times[1]}月${times[2]}日`
      } else {
        return '--'
      }
    },
    filterUserStatus(status) {
      if (status) {
        return USER_STATUS[status]
      } else {
        return '--'
      }
    },
  },
  methods: {
    /* 头部样式 */
    headerStyle({ row, column, rowIndex, columnIndex }) {
      return 'headerStyle'
    },
    rowClass({ row, rowIndex }) {
      if (row.isMainLead === 1) {
        return 'rowClass rowClassLead'
      } else {
        return 'rowClass'
      }
    },
    delAccount(row) {
      // 删除账号的同时也会将关联的机构删除，请谨慎操作
      const userId = localStorage.pskh_userId || JSON.parse(localStorage.PSKH_USERINFO)?.userId
      let delTips = ''
      if (row.id === userId) {
        delTips = '确定删除当前登录账号？删除登录账号后系统会自动退出！'
      } else {
        delTips = '确定删除该账号？'
      }
      this.$confirm(delTips, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$emit('del-account', row, userId)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除',
          })
        })
    },
    editAccount(row) {
      this.$emit('edit-account', row)
    },
    /* 拖拽 */
    treeDrop() {
      let draggedItem = null
      let relatedItem = null
      let willInsertAfter1 = null
      const isDrop = true
      this.$nextTick(() => {
        const xTable = this.$refs.xTable
        this.sortable2 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
          handle: '.drag-btn',
          // 在列表中或列表之间移动项目时的事件
          onMove: ({ dragged, related, willInsertAfter }) => {
            // if (!this.searchForm.orgId) {
            //   this.$message.error('请选择机构，并在同一机构内进行排序调整')
            //   return
            // }
            draggedItem = xTable.getRowNode(dragged).item
            relatedItem = xTable.getRowNode(related).item
            willInsertAfter1 = willInsertAfter
            // console.log(draggedItem);
            // console.log(relatedItem);
            // console.log(willInsertAfter);
          },
          onEnd: () => {
            if (isDrop) {
              const param = {
                operate: willInsertAfter1 ? 'after' : 'before',
                operateId: draggedItem.id,
                targetId: relatedItem.id,
                tenantId: localStorage.pskh_tenantId,
              }
              this.$emit('drop-account', param)
            } else {
              this.$emit('drop-account')
            }
          },
        })
      })
    },
  },
  beforeDestroy() {
    if (this.sortable2) {
      this.sortable2.destroy()
    }
  },
}
</script>
<style lang="scss" scoped>
.account-table {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;

  .search-box {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .search-left {
      display: flex;
      align-items: center;
      width: 70%;
      .search-item {
        max-width: 240px;
      }
      .search-item + .search-item {
        margin-left: 20px;
      }
      .search-inp {
        width: 240px;
      }
      .el-icon-search {
        cursor: pointer;
      }
    }
  }

  .table-box {
    flex: 1;
    position: relative;

    .table-con {
      ::v-deep .headerStyle {
        background-color: #f0f4f9;

        .vxe-cell {
          color: #333333;
          font-size: 14px;

          span {
            font-weight: 600;
          }
        }
      }

      ::v-deep .rowClass {
        .vxe-cell {
          color: #666666;
          font-size: 14px;

          p,
          div,
          span {
            font-size: 14px;
          }
        }
      }

      ::v-deep .rowClassLead {
        height: 80px;
        .vxe-cell {
          color: #666666;
          font-size: 14px;

          p,
          div,
          span {
            font-size: 14px;
          }
        }
        .triangle-tips {
          position: absolute;
          right: 0;
          height: 40px;
          width: 40px;
          display: flex;
          align-items: center;
          span {
            position: absolute;
            // top: 0;
            right: 0;
            width: 0;
            height: 0;
            em {
              position: absolute;
              height: 40px;
              width: 40px;
              line-height: 40px;
              text-align: center;
              color: #2b78f1;
              font-style: normal;
              font-size: 12px;
              transform: scale(0.5);
            }
          }
          &.top-left {
            left: 0;
            top: 0;
            span {
              top: 0;
              border-right: 40px solid transparent;
              border-top: 40px solid#62a2fc;
            }
            em {
              top: -46px;
              left: -7px;
              transform: rotate(-45deg);
              -webkit-transform: rotate(-45deg);
            }
            &.bg-red {
              span {
                border-top-color: #d6e6ff;
              }
            }
          }
        }
      }
    }
  }

  .bg-pagination {
    margin-top: 10px;
  }
}
/deep/.drag-btn {
  cursor: move;
}
</style>
